package cn.scu.ne04jdemo.controller;

import cn.scu.ne04jdemo.entitiy.User;
import cn.scu.ne04jdemo.service.UserService;
import cn.scu.ne04jdemo.util.JsonResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/users/login")
    public String login(@RequestBody User user) {
        System.out.println("===========");
        System.out.println(user);
        int loginResult = userService.login(user);
        /*System.out.println(userByName.getPassword());
        System.out.println(user.getPassword());*/
        if (loginResult == 1) {
            return "ok";
        } else {
            return "error";
        }
    }

    @PostMapping("/users/register")
    public String register(@RequestBody User user) {
        System.out.println("===========");
        System.out.println(user);
        int registerResult = userService.register(user);
        /*System.out.println(userByName.getPassword());
        System.out.println(user.getPassword());*/
        if (registerResult == 1) {
            return "ok";
        } else {
            return "error";
        }
    }

    @GetMapping("/users/list")
    public IPage<User> getUserList(@RequestParam Map<String, String> params) {
        int pageNum = Integer.parseInt(params.getOrDefault("pageNum", "1"));
        int pageSize = Integer.parseInt(params.getOrDefault("pageSize", "10"));
        IPage<User> page = userService.page(new Page<User>(pageNum, pageSize));
        return page;
    }

    @GetMapping("/users/{userId}")
    public ResponseEntity<JsonResponse> getUserById(@PathVariable String userId) {
        User user = userService.getById(userId);
        return ResponseEntity.ok(JsonResponse.success(user));
    }

    @PutMapping("/users/{userId}")
    public ResponseEntity<Boolean> updateUser(@PathVariable String userId, @RequestBody User user) {
        boolean result;
        if (user == null || !user.getId().toString().equals(userId)) {
            result = false;
        } else {
            result = userService.updateById(user);
        }
        return ResponseEntity.ok(result);
    }
    
    @CrossOrigin
    @DeleteMapping("/users/{userId}")
    public ResponseEntity<Boolean> deleteUser(@PathVariable String userId) {
        boolean result = userService.removeById(userId);
        return ResponseEntity.ok(result);
    }

    @GetMapping("/users/allUser")
    public List<User> getAllUser() {
        List<User> users = userService.list();
        return users;
    }
}
